import path from 'path'
import fs from 'fs'
import { exec as execCb } from 'child_process'
import { promisify } from 'util'
import plist from 'simple-plist'

const exec = promisify(execCb)
const readFile = promisify(plist.readFile)

async function getIconFile(appFileInput: string) {
  try {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const data: any = await readFile(path.join(appFileInput, 'Contents', 'Info.plist'))
    const iconFile = path.join(appFileInput, 'Contents', 'Resources', data.CFBundleIconFile)
    const iconFiles = [iconFile, iconFile + '.icns', iconFile + '.tiff']

    for (const file of iconFiles) {
      if (fs.existsSync(file)) {
        return file
      }
    }
  } catch (err) {
    // Ignore errors
  }

  return ''
}

const tiffToPng = async (iconFile: string, pngFileOutput: string): Promise<void> => {
  await exec(
    `sips -s format png '${iconFile}' --out '${pngFileOutput}' --resampleHeightWidth 256 256`
  )
}

export async function app2png(
  appFileInput: string,
  pngFileOutput: string
): Promise<{ ok: boolean; error? }> {
  try {
    const iconFile = await getIconFile(appFileInput)
    if (iconFile === '') {
      return { ok: false }
    }

    await tiffToPng(iconFile, pngFileOutput)
    return { ok: true }
  } catch (error) {
    console.error('Failed to convert the icon file to PNG:', error)
    return { ok: false, error }
  }
}
